import React from 'react'
import { connect } from 'dva'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import { Page } from 'components'
import OrganizationTree from './Tree'
import { Row, Col, Button, notification, Modal } from 'antd'
import OrganizationForm from './OrganizationFormModal'
import DistributorForm from './DistributorFormModal'
import Table from './Table'
import BindSteps from './BindSteps'
import {ROOT_ID} from 'utils/organizationConstant'

const Organizations = ({location, dispatch, organization, distributor, bindUser, user, role, loading}) => {
  const {
    tree,
    currentItem,
    modalVisible: modalOrganizationVisible,
    type: organizationType,
    userIds,
    users,
    userSelectModalVisible,
    parentItem,
    searchKeyword = '',
  } = organization

  const {
    item: distributorItem,
    type: distributorType,
    modalVisible: modalDistributorVisible
  } = distributor

  const {
    user: bindUserItem,
    modalVisible: bindUserModalVisible,
    step: bindUserStep,
    roleIds,
    rolesModalVisible
  } = bindUser

  const {
    items: userItems,
    pagination: userPagination,
    roles
  } = user

  const {
    items: roleItems,
  } = role
  const user4SearchItems = role.userItems
  const user4SearchPagination = role.userPagination
  const breadcrumbList = [
    {
      title: '系统管理'
    },
    {
      title: '组织机构管理'
    },
  ]

  /**
   * 树的Props
   * @type {{dataSource: *, defaultExpandAll: boolean, showLine: boolean, distributorType: *, onSelect: onSelect}}
   */
  const treeProps = {
    dataSource: tree,
    defaultExpandAll: true,
    showLine: true,
    showIcon: false,
    distributorType: distributorType,
    onSelect: (datum) => {
      dispatch({
        type: 'organization/onChoose',
        payload: {
          ...datum
        }
      })

      dispatch({
        type: 'distributor/onChoose',
        payload: {
          ...datum
        }
      })
    },
    dispatch,
    searchKeyword
  }

  const onAdd = () => {
    dispatch({
      type: 'organization/create',
      payload: {}
    })
  }

  const onEdit = () => {
    dispatch({
      type: 'organization/edit',
      payload: {}
    })
  }

  const onDelete = () => {
    if (_.isEmpty(currentItem)) {
      return
    }
    dispatch({
      type: 'organization/onDelete',
      payload: {...currentItem}
    })
  }

  const onSetDistributor = () => {
    dispatch({
      type: 'distributor/setDistributor',
      payload: {}
    })
  }

  /**
   * 选择人员的模态框
   */
  const onSelectUser = () => {
    dispatch({
      type: 'role/queryUser',
      payload: {
        isEnabled:true
      }
    })
    dispatch({
      type: 'organization/onSelectUser',
      payload: {}
    })
  }

  /**
   * 解绑人员
   */
  const onUnbindUser = () => {
    dispatch({
      type: 'organization/onUnbindUser',
      payload: {
        id: currentItem.id,
        ids: userIds
      }
    })
  }

  const onBindUser = () => {
    dispatch({
      type: 'bindUser/showModal',
      payload: {}
    })
  }

  /**
   * 启用禁用门店
   */
  const modifyDistributorEnable = () => {
    dispatch({
      type: 'distributor/onModifyEnable',
      payload: distributorItem
    })
  }

  /**
   * 门店模态框设置
   * @type {{title: string, visible: *, onOk: onOk, confirmLoading: boolean, onCancel: onCancel, item: {}, destroyOnClose: boolean}}
   */
  const distributorModalProps = {
    title: (distributorType === 'create' ? '添加' : '修改') + '门店信息',
    visible: modalDistributorVisible,
    distributorType:distributorType,
    onOk: (datum) => {
      distributorType === 'create' ?
        dispatch({
          type: 'distributor/onStore',
          payload: {
            organization: currentItem,
            item: datum,
          }
        }) : dispatch({
          type: 'distributor/onUpdate',
          payload: {
            organization: currentItem,
            item: datum,
            id: distributorItem.id
          }
        })
    },
    confirmLoading: false,
    onCancel: () => {
      dispatch({
        type: 'distributor/hideModal',
        payload: {}
      })
    },
    item: distributorType === 'create' ? currentItem : distributorItem,
    destroyOnClose: true,
  }

  /**
   * 组织机构
   * @type {{title: string, visible: *, onOk: onOk, confirmLoading: boolean, onCancel: onCancel, item: {}, destroyOnClose: boolean}}
   */
  const organizationModalProps = {
    title: (organizationType === 'create' ? '添加' : '修改') + '组织机构',
    visible: modalOrganizationVisible,
    onOk: (datum) => {
      if (organizationType === 'create') {
        datum.rank = (parseInt(currentItem.rank) + 1) || 0
        dispatch({
          type: 'organization/onStore',
          payload: {...datum}
        })
      } else {
        datum.id = currentItem.id
        datum.parentId = currentItem.parentId
        datum.rank = currentItem.rank
        datum.version = currentItem.version
        dispatch({
          type: 'organization/onUpdate',
          payload: {...datum}
        })
      }

    },
    confirmLoading: false,
    onCancel: () => {
      dispatch({
        type: 'organization/hideModal',
        payload: {}
      })
    },
    item: organizationType === 'create' ? {} : currentItem,
    parentItem: parentItem,
    destroyOnClose: true,
    organizationType:organizationType
  }

  /**
   * 用户绑定步骤条Modal
   * @type {{title: string, visible: *, confirmLoading: boolean, destroyOnClose: boolean, onCancel: onCancel, footer: boolean, width: number, bindUserStep: *}}
   */
  const bindModalProps = {
    title: '用户绑定',
    visible: bindUserModalVisible,
    confirmLoading: false,
    destroyOnClose: true,
    onCancel: () => {
      dispatch({
        type: 'bindUser/hideModal',
        payload: {}
      })
      dispatch({
        type: 'bindUser/destroyUser',
        payload: {}
      })
    },
    footer: false,
    width: 800,
    bindUserStep,
    dispatch,
    bindUserItem,
    roleItems,
    roleIds,
    currentItem,
  }

  /**
   * 已选用户列表的设置
   * @type {{dataSource: *, selectedRowKeys: *, onSelectUserRows(*=, *): void}}
   */
  const userListProps = {
    dataSource: users,
    selectedRowKeys: userIds,
    rolesModalVisible,
    roles,
    dispatch,
    loading,
    onSelectUserRows (selectedRowKeys, selectRows) {
      dispatch({
        type: 'organization/bindUser',
        payload: {
          userIds: selectedRowKeys
        }
      })
    },
    showRolesModal (status) {
      dispatch({
        type: 'bindUser/showRolesModal',
        payload: status
      })
    },
    showRole (record) {
      dispatch({
        type: 'user/getUserRoles',
        payload: record.id
      })
    },
  }

  /**
   * 搜索用户的modal框
   * @type {{visible: *, title: string, width: number, destroyOnClose: boolean, wrapClassName: string, onOk(): void, onCancel(): void, onSelectRows: onSelectRows, okText: string, cancelText: string, dataSource: *, pagination: *, dispatch: *, toBeBoundUser: *}}
   */
  const searchUserModalProps = {
    visible: userSelectModalVisible,
    title: '选择用户',
    width: 1000,
    destroyOnClose: true,
    wrapClassName: 'vertical-center-modal',
    okText: '确认',
    cancelText: '取消',
    dataSource: user4SearchItems,
    pagination: user4SearchPagination,
    dispatch,
    toBeBoundUser: userIds,
    rolesModalVisible,
    roles,
    onOk () {
      // 角色用户绑定
      if(_.isEmpty(userIds) || userIds.length===0){
        Modal.error({
          title:'错误',
          content:'请至少选择一个用户！'
        })
        return
      }
      dispatch({
        type: 'organization/onBindUser',
        payload: {ids: userIds, id: currentItem.id}
      })
    },
    onCancel () {
      dispatch({
        type: 'organization/hideModal',
        payload: {}
      })
    },
    onSelectRows: (selectedRowKeys) => {
      dispatch({
        type: 'organization/createSelectUserIds',
        payload: selectedRowKeys
      })
    },
    showRolesModal (status) {
      dispatch({
        type: 'bindUser/showRolesModal',
        payload: status
      })
    },
    showRole (record) {
      dispatch({
        type: 'user/getUserRoles',
        payload: record.id
      })
    },
  }

  /**
   * Col的样式设置
   * @type {{xs: number, sm: number, style: {marginBottom: number}}}
   */
  const ColProps = {
    xs: 24,
    sm: 24,
    style: {
      marginBottom: 16
    }
  }

  return (
    <PageHeaderLayout title='组织机构管理' breadcrumbList={breadcrumbList}>
      <Page inner>
        <Row>
          <Col span={12}>
            <Row gutter={24}>
              <Col {...ColProps}>
                <Button type="primary" size="small" className="margin-right" onClick={onAdd}>添加</Button>
                {typeof currentItem.id !== 'undefined' &&
                <Button type="primary" size="small" className="margin-right" onClick={onEdit}>修改</Button>}
                {/*{typeof currentItem.id !== 'undefined' &&*/}
                {/*<Button type="primary" size="small" className="margin-right" onClick={onDelete}>删除</Button>}*/}
                {distributorType === 'create' && typeof currentItem.id !== 'undefined' &&
                <Button type="primary" size="small" className="margin-right" onClick={onSetDistributor}>设置为门店</Button>}
                {distributorType === 'update' && typeof currentItem.id !== 'undefined' &&
                <Button type="primary" size="small" className="margin-right" onClick={onSetDistributor}>修改门店信息</Button>}
                {distributorType === 'update' && distributorItem.enabled === false && typeof currentItem.id !== 'undefined' &&
                <Button type="primary" size="small" className="margin-right" onClick={modifyDistributorEnable}>启用门店</Button>}
                {distributorType === 'update' && distributorItem.enabled === true && typeof currentItem.id !== 'undefined' &&
                <Button type="primary" size="small" className="margin-right" onClick={modifyDistributorEnable}>禁用门店</Button>}
              </Col>
            </Row>
            {tree.length ?
              <OrganizationTree {...treeProps}/> : null}
            <OrganizationForm {...organizationModalProps}/>
            <DistributorForm {...distributorModalProps}/>
            {bindUserModalVisible && <BindSteps {...bindModalProps}/>}
          </Col>
          <Col span={12}>
            <Row gutter={24}>
              <Col {...ColProps}>
                {typeof currentItem.id !== 'undefined' &&
                <Button type="primary" size="small" className="margin-right" onClick={onSelectUser}>绑定人员</Button>}
                {typeof currentItem.id !== 'undefined' &&
                <Button type="primary" size="small" className="margin-right" onClick={onUnbindUser}>解绑人员</Button>}
              </Col>
              <Col {...ColProps}>
                <Table userListProps={userListProps} searchUserModalProps={searchUserModalProps}/>
              </Col>
            </Row>
          </Col>
        </Row>
      </Page>
    </PageHeaderLayout>
  )
}

export default connect(({organization, distributor, bindUser, user, loading, role}) => ({
  organization,
  distributor,
  bindUser,
  user,
  loading,
  role
}))(Organizations)
